package com.eveinfo.display.setting;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.eveinfo.EveInfo;
import com.eveinfo.R;
import com.eveinfo.api.accessors.CharacterList;
import com.eveinfo.api.character.list.ApiCharacter;
import com.eveinfo.tools.ConfigFileException;
import com.eveinfo.tools.Logging;
import com.eveinfo.tools.Pilot;
import com.eveinfo.tools.Setting;

public class SettingCharacterView extends Activity {

	private static final String SDCARD = "/sdcard/";

	static final int DIALOG_ADDPILOT1 = 0;
	static final int DIALOG_ADDPILOT2 = 1;
	static final int DIALOG_EDITPILOT = 2;

	private Context context;
	private final HashSet<String> set;
	private List<String> nameList;
	private CharacterList characterList;
	private int currentUserId;
	private String currentApiKey;
	private ArrayList<Pilot> pilots;
	private PilotListAdapter pilotListAdapter;
	private int selectedItem;

	public SettingCharacterView() {
		this.context = this;
		set = new HashSet<String>();
		nameList = null;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.settingpilot);
		pilots = EveInfo.getPilots();

		Button addB = (Button) findViewById(R.id.BSettingPilotAdd);
		addB.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(DIALOG_ADDPILOT1);
			}
		});

		Button loadB = (Button) findViewById(R.id.BSettingPilotLoad);
		loadB.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					pilots = Setting.readOptions(context, SDCARD);
					pilotListAdapter.refreshData(pilots);
					EveInfo.setPilots(pilots);
					EveInfo.getData().update();
				} catch (ConfigFileException e) {
					AlertDialog.Builder builder = new AlertDialog.Builder(context);
					builder.setTitle("Configuration File Error");
					builder.setMessage(e.getMessage());
					builder.show();
					e.printStackTrace();
				}
			}
		});

		ListView listView = (ListView) findViewById(R.id.LVSettingPilotList);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parentView, View childView, int position, long id) {
				selectedItem = position;
			}
		});
		pilotListAdapter = new PilotListAdapter(this, listView, pilots);

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		EveInfo.setPilots(pilots);
		Setting.writeOption(this, pilots);
	}

	public int getSelectedItem() {
		return selectedItem;
	}

	public void setSelectedItem(int selectedItem) {
		this.selectedItem = selectedItem;
		showDialog(DIALOG_EDITPILOT);
	}

	@Override
	protected void onPrepareDialog(int id, final Dialog dialog) {
		switch (id) {
		case DIALOG_ADDPILOT1:
			Button submit = (Button) dialog.findViewById(R.id.BPilotAdd1Submit);
			submit.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					String userId = ((EditText) dialog.findViewById(R.id.ETSettingUserID)).getText().toString();
					String apiKey = ((EditText) dialog.findViewById(R.id.ETSettingAPIKey)).getText().toString();
					dialog.dismiss();
					removeDialog(DIALOG_ADDPILOT1);
					submit(userId, apiKey);
				}
			});
			return;
		case DIALOG_ADDPILOT2:
			LinearLayout layout = (LinearLayout) dialog.findViewById(R.id.LLSetting2);
			for (String name : nameList) {
				layout.addView(createCheckBox(name));
			}

			Button add = (Button) dialog.findViewById(R.id.BSetting2Add);
			add.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					addPilot();
					dialog.dismiss();
					removeDialog(DIALOG_ADDPILOT2);
				}
			});

			Button cancel = (Button) dialog.findViewById(R.id.BSetting2Cancel);
			cancel.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.dismiss();
					removeDialog(DIALOG_ADDPILOT2);
				}
			});
			return;
		case DIALOG_EDITPILOT:
			Pilot pilot = pilots.get(selectedItem);
			final EditText userName = (EditText) dialog.findViewById(R.id.ETSettingPilotUserName);
			userName.setText(pilot.getName());
			final EditText userId = (EditText) dialog.findViewById(R.id.ETSettingPilotUserID);
			userId.setText("" + pilot.getUserId());
			final EditText characterId = (EditText) dialog.findViewById(R.id.ETSettingPilotCharacterID);
			characterId.setText("" + pilot.getCharacterId());
			final EditText apiKey = (EditText) dialog.findViewById(R.id.ETSettingPilotAPIKey);
			apiKey.setText(pilot.getApiKey());

			Button delete = (Button) dialog.findViewById(R.id.BSettingPilotDelete);
			delete.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					final Pilot remove = pilots.remove(selectedItem);
					EveInfo.getData().removeCharacterData(remove.getCharacterId());
					EveInfo.setPilots(pilots);
					Setting.writeOption(context, pilots);
					dialog.dismiss();
					removeDialog(DIALOG_EDITPILOT);
					pilotListAdapter.notifyDataSetChanged();
				}
			});

			Button save = (Button) dialog.findViewById(R.id.BSettingPilotSave);
			save.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					modifyPilot(userName.getText().toString(), Integer.parseInt(userId.getText().toString()), Integer
							.parseInt(characterId.getText().toString()), apiKey.getText().toString());
					dialog.dismiss();
					removeDialog(DIALOG_EDITPILOT);
				}
			});
			return;
		default:
			return;
		}
	}

	protected Dialog onCreateDialog(int id) {
		final Dialog dialog;
		switch (id) {
		case DIALOG_ADDPILOT1:
			dialog = new Dialog(this);
			dialog.setContentView(R.layout.pilotadd1);
			dialog.setTitle("New Character");
			return dialog;
		case DIALOG_ADDPILOT2:
			dialog = new Dialog(this);
			dialog.setContentView(R.layout.pilotadd2);
			dialog.setTitle("New Character");

			return dialog;
		case DIALOG_EDITPILOT:
			dialog = new Dialog(this);
			dialog.setContentView(R.layout.pilotinfo);
			dialog.setTitle("Character");
			return dialog;
		default:
			dialog = null;
			return dialog;
		}
	}

	private CheckBox createCheckBox(final String name) {
		CheckBox box = new CheckBox(this);
		box.setText(name);
		box.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					set.add(name);
				} else {
					set.remove(name);
				}
			}
		});
		return box;
	}

	private void submit(String userId, String apiKey) {
		try {
			int id = Integer.parseInt(userId);
			currentUserId = id;
			currentApiKey = apiKey;
			characterList = new CharacterList(id, 0, apiKey);
			nameList = characterList.getCharacterNameList();
			if(nameList == null){
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage("Did not retrieve the charactere list");
				builder.show();
				return;
			}
			showDialog(DIALOG_ADDPILOT2);

		} catch (NumberFormatException e) {
			Logging.getInstance().e(e);
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Wrong Api Key or User ID");
			builder.show();
		} catch (Exception e) {
			Logging.getInstance().e(e);
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(e.getMessage());
			builder.show();
		}
	}

	private void addPilot() {
		for (String s : set) {
			for (ApiCharacter character : characterList.getCharacterList()) {
				if (character.getName().equals(s)) {
					Pilot pilot = new Pilot();
					pilot.setName(s);
					pilot.setUserId(currentUserId);
					pilot.setCharacterId(character.getCharacterID());
					pilot.setApiKey(currentApiKey);
					pilots.add(pilot);
				}
			}
		}
		pilotListAdapter.notifyDataSetChanged();
	}

	private void modifyPilot(String userName, int userId, int characterId, String apiKey) {
		Pilot pilot = pilots.get(selectedItem);
		pilot.setName(userName);
		pilot.setUserId(userId);
		pilot.setCharacterId(characterId);
		pilot.setApiKey(apiKey);
		pilotListAdapter.notifyDataSetChanged();
		pilotListAdapter.notifyDataSetChanged();
	}

}